#!/usr/bin/Rscript --vanilla
# this file creates a nuggetShape File for one strategy.
# Input: consistentBestPatterns/vx_y_consistentPatterns.Rdata
# Output: stratlab/nuggetShapes/vx_y_nuggetShapes.Rdata
# this script is run once for each strategy.

# global parameters follow
inputDir <- "/home/voellenk/Dropbox/constellation/consistentBestPatterns"
outputDir <- "/home/voellenk/stratlab_workdir/stratlab/nuggetShapes"

# load required packages
suppressPackageStartupMessages(library(optparse))

option_list <- list(
  make_option(c("--strategy"), default="notSpecified",
              help="id of strategy to process [default \"%default\"]\n
                    Example: --strategy=v1_2"),
  make_option(c("-v", "--verbose"), action="store_true", default=FALSE,
              help="Print extra output [default]")
)

opt <- parse_args(OptionParser(option_list=option_list))
args <- commandArgs(trailingOnly=TRUE)

# some helper functions

# calculates mean.BS, sd.BS, mean.SS, sd.SS, mean.N, sd.N for each pattern
# example: dfLine
#          BS_3_1    SS_3_1      N_3_1    BS_3_2 SS_3_2 N_3_2    BS_3_3    SS_3_3 N_3_3    BS_3_4    SS_3_4 N_3_4
# 274a5fd3 0.8594898 0.6003236   214 0.7950502 0.572706   238 0.8202838 0.6246108   234 0.8436136 0.6391052   231
calcMeanSDMetrics <- function(dfLine) {
  cnames <- colnames(dfLine)
  BS <- unlist(dfLine[1,grep("^BS_", cnames)]) # vector of buy signals
  SS <- unlist(dfLine[1,grep("^SS_", cnames)]) # vector of sell signals
  N <- unlist(dfLine[1,grep("^N_", cnames)])   # vector of number of observations
  mean.BS <- mean(BS)
  sd.BS <- sd(BS)
  mean.SS <- mean(SS)
  sd.SS <- sd(SS)
  mean.N <- mean(N)
  sd.N <- sd(N)
  return(data.frame(mean.BS, sd.BS, mean.SS, sd.SS, mean.N, sd.N))
}

# scan input directory for qualified .Rdata files
reportFiles <- list.files(inputDir, pattern="^v.*.Rdata$")
this.file <- paste0(opt$strategy, "_consistentPatterns.Rdata")
if (this.file %in% reportFiles) {
  load(paste(inputDir, this.file, sep="/"))
  if (!"report" %in% ls()) {
    stop(paste("ERROR: Could not load report list in file", this.file))
  }
} else {
  stop(paste("ERROR: File", this.file, "not found."))
}

# scan report list and form nuggetShape data.frame
distinctPeriods <- names(report)
nS <- data.frame()  # nS stands for nuggetShapes
for (i in 1:length(distinctPeriods)) {
  this.period <- distinctPeriods[i] # list label contains p (example: p3, p5, ...)
  period <- as.numeric(sub("[a-z]", "", distinctPeriods[i])) # numeric period
  for (signal in c("b", "s")) {
    for (j in 1:nrow(report[[this.period]][[signal]])) {
      ID <- rownames(report[[this.period]][[signal]][j,])
      cnames <- colnames(report[[this.period]][[signal]][j,])
      metricCols <- grep("(BS|SS|N)_[0-9]+_[0-9]+", cnames)
      nonMetricCols <- grep("(BS|SS|N)_[0-9]+_[0-9]+", cnames, invert=TRUE)
      summaryMetrics <- calcMeanSDMetrics(report[[this.period]][[signal]][j,metricCols])
      this.line <- data.frame(period, signal, ID, 
                              report[[this.period]][[signal]][j,nonMetricCols], 
                              calcMeanSDMetrics(report[[this.period]][[signal]][j,metricCols]))
      nS <- rbind(nS, this.line)
    }
  }
}
# at this time the data.frame nuggetShapes contains all available promising patterns

# filter out not-so consistent pattern among different seeds
nS <- rbind(nS[nS$mean.BS - nS$sd.BS/2 > nS$mean.SS + nS$sd.SS/2, ],
            nS[nS$mean.SS - nS$sd.SS/2 > nS$mean.BS + nS$sd.BS/2, ])

# order by magnitude of signal
nS <- nS[with(nS, order(-abs(mean.BS-mean.SS))), ]

nS

# save finished nS data.frame into file vx_y_nuggetShapes.Rdata
targetFilename <- paste0(opt$strategy, "_nuggetShapes.Rdata")
save(nS, file=paste(outputDir, targetFilename, sep="/"))
